package com.shuimin.group;

import com.shuimin.group.mid.time.AppTimer;
import com.shuimin.group.model.weixin.WeixinUser;
import com.shuimin.group.service.WeixinUserService;
import com.shuimin.group.service.WeixinService;
import pond.common.FILE;
import pond.common.JSON;
import pond.common.S;
import pond.common.STRING;
import pond.db.DB;
import pond.db.connpool.ConnectionPool;
import pond.web.*;

import java.io.IOException;
import java.util.*;

public class App {

    public static final DB DB = new DB(ConnectionPool.c3p0(FILE.loadProperties("db.conf")));
    public static final String APP_WEIXIN_USER_INFO = "app_weixin_user_info";
    public static final String SERVER_WEIXIN_USER_INFO = "server_weixin_user_info"; 
    public static final String INNER_API_AUTH_TOKEN = "ad848030468754bc9da991bde3070dccp";
    public static String getUserId(Request req)
    {
        WeixinUser weixinUser = Session.get(req).get(App.APP_WEIXIN_USER_INFO);
        return weixinUser.id();
        //return "1d47042e52ca48d5bd44ed3491ca4317";//kun
        //return "08d01cabf0894f679201450c988ca150";//fei
    }
    public static WeixinUser getLoginUser(HttpCtx ctx)
    {
        return Session.get(ctx).get(App.APP_WEIXIN_USER_INFO);
    }
    public static void main(String args[]) {
        /* 启动定时器任务 */
        AppTimer.init();

        Pond.init((Pond app) -> {
            Mid auth = (req, resp) -> {
                Session session = Session.get(req);
                WeixinUser weixinUser = session.get(APP_WEIXIN_USER_INFO);
                if (null == weixinUser) {
                    resp.send(403,"can not find weixinUser info, please login first");
                    return;
                }
            };

            Mid inner_api_auth = (req, resp) -> {
                String token = req.param("token");
                if (STRING.isBlank(token) || !INNER_API_AUTH_TOKEN.equals(token)) {
                    resp.send(404,"token is not valid");
                    return;
                }
            };


            app.get("/auth", Session.install(7000), (req, resp) -> {
                Map<String,Object> dataMap = req.toMap();
                Map <String,Object> retMap = new HashMap<>();
                S.echo(dataMap.toString());
                if(null == dataMap.get("code"))
                {
                    resp.send(403, "request has no code info");
                    return;
                }
                String code = dataMap.get("code").toString();
                Map<String,String> ret = new HashMap<>();
                try {
                    ret = WeixinService.getAppSessionByCode(code);
                } catch (IOException e) {
                    resp.send(404, "failed to get session_key from weixin server");
                    e.printStackTrace();
                    return;
                }
                if (null != ret)
                {
                    if (!ret.containsKey("openid"))
                    {
                        resp.send(500, "jscode2session:"+JSON.stringify(ret));
                        return;
                    }
                    Session ses = Session.get(req);
                    ses.set(SERVER_WEIXIN_USER_INFO, ret);
                    ses.save();
                    String openid = ret.get("openid");
                    App.DB.post(t-> {
                        WeixinUser weixinUser = WeixinUserService.get(openid);
                        if (weixinUser != null)
                        {
                            ses.set(APP_WEIXIN_USER_INFO, weixinUser);
                            ses.save();
                            retMap.put(APP_WEIXIN_USER_INFO,weixinUser);
                        }
                    });
                    S.echo(ses.get(SERVER_WEIXIN_USER_INFO).toString());
                    retMap.put("pond-session",ses.id());
                    resp.render(Render.json(retMap));
                }
                else{
                    resp.send(404,"not found");
                    return;
                }
            });
            app.get("/checkSession", Session.install(7000), (req, resp) -> {
                Session session = Session.get(req);
                WeixinUser weixinUser = session.get(APP_WEIXIN_USER_INFO);
                if (null == weixinUser) {
                    resp.send(403,"can not find weixinUser info, please login first");
                    return;
                }
                Map <String,Object> retMap = new HashMap<>();
                retMap.put("pond-session", session.id());
                retMap.put(APP_WEIXIN_USER_INFO, weixinUser);
                resp.render(Render.json(retMap));
            });
            app.get("/login", Session.install(7000), (req, resp) -> {
/*
                WeixinUser weixinUser = WeixinUserService.getUserById("08d01cabf0894f679201450c988ca150");
                Session ses = Session.get(req);
                ses.set(APP_WEIXIN_USER_INFO, weixinUser);
                ses.save();
                resp.send(200,"ok");*/
                Session ses = Session.get(req);
                Map<String,String> map = ses.get(SERVER_WEIXIN_USER_INFO);
                if (null == map)
                {
                    resp.send(403, "please access with code first");
                    return;
                }
                WeixinUser weixinUser = ses.get(APP_WEIXIN_USER_INFO);
                if (null == weixinUser) {

                    String openid = map.get("openid");
                    Map<String,Object> dataMap = req.toMap();
                    S.echo(dataMap.toString());
                    Map<String,Object> userInfo = (Map<String,Object>)JSON.parse(dataMap.get("userInfo").toString());
                    weixinUser = WeixinUserService.mergeObj(openid,userInfo);
                    ses.set(APP_WEIXIN_USER_INFO, weixinUser);
                    ses.save();

                    resp.send(200,"login ok");
                    return;

                }
                else
                {
                    resp.send(200,"login ok");
                    return;
                }

            });

            app.use("/weixin/*",new WEIXIN());
            app.use("/wschat/*",
                    CtxHandler.express(Session.install(7000)),
                    CtxHandler.express(auth),
                    new WSCHAT());

            app.use("/api/*",
                    CtxHandler.express(Session.install(7000)),
                    CtxHandler.express(auth),
                    new Router()
                        .use("/group/*",  new GROUP())
                        .use("/sign/*",  new SIGN())
                        .use("/place/*", new PLACE())
                        .use("/follow/*", new FOLLOW())
                        .use("/weixin_user/*", new WEIXIN_USER())
            );
            app.use("/inner_api/*", CtxHandler.express(inner_api_auth),
                    new Router()
                            .use("/group/*", new INNER_GROUP())
                            .use("/import/*", new INNER_IMPORT())
                            .use("/weixin_user/*", new INNER_WEIXIN_USER())
            );
            app.get("/*", app._static("assets"));
            app.otherwise(InternalMids.FORCE_CLOSE);
        }).listen(1234);
    }
}
